package com.project.sianet.fragment;

import java.util.ArrayList;
import java.util.List;

import org.apache.http.HttpVersion;
import org.apache.http.params.BasicHttpParams;
import org.apache.http.params.HttpProtocolParams;
import org.apache.http.protocol.HTTP;

import android.app.Activity;
import android.app.ProgressDialog;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.AdapterView.OnItemClickListener;

import com.project.sianet.MainActivity;
import com.project.sianet.R;
import com.project.sianet.data.AlumnoArrayAdapter;
import com.project.sianet.data.Client.AlumnoClient;
import com.project.sianet.data.HttpClient.AlumnoHttpClient;
import com.project.sianet.entidades.*;
import com.project.sianet.util.AlertDialogManager;
import com.project.sianet.util.ConnectionDetector;
import com.project.sianet.util.SessionManager;
import com.project.sianet.util.extenders.SianetApplication;

public class MisHijosFragment extends Fragment {
	
	private int mTitleFrag;
	private String lastRequestURI;
    private AlumnoClient client;
    private ProgressDialog progressDialog = null;

    // Clase Connection detector
    ConnectionDetector cd;
	
    public MisHijosFragment() {}
    
    public static final MisHijosFragment newInstance() {
    	MisHijosFragment f = new MisHijosFragment();
    	Bundle args = new Bundle();
    	args.putInt("mTitleFrag", R.string.title_bar_mishijos);
    	f.setArguments(args);
    	return f;
    }
	
	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
		super.onCreateView(inflater, container, savedInstanceState);
		return inflater.inflate(R.layout.fragment_mishijos, null);
	}
	
	@Override
	public void onActivityCreated(Bundle savedInstanceState) {
		super.onActivityCreated(savedInstanceState);

		// Creo la instancia de Connection detector
        cd = new ConnectionDetector(getActividad().getApplicationContext());
		
        mTitleFrag = getArguments().getInt("mTitleFrag");
		
		cargarmAlumnos();
		
		TextView title = (TextView)this.getActivity().findViewById(R.id.tv_title);
		title.setText(mTitleFrag);
        
	}
	
    private void onSelectedHijoItemClick(AdapterView<?> parent, View view, int position, long id) { 
    	AlumnoArrayAdapter arrayAlumno = (AlumnoArrayAdapter) parent.getAdapter();
    	Alumno alu = arrayAlumno.getItem(position);
    	Fragment newContent = MisHijosOpcionesFragment.newInstance(alu);
    	switchFragment(newContent);
    }
    
    private void switchFragment(Fragment fragment) {
 		if (getActivity() == null)
 			return;
 		
 		if (getActivity() instanceof MainActivity) {
 			MainActivity ma = (MainActivity) getActivity();
 			ma.switchContent(fragment);
 		}
 	}
	
	private void cargarmAlumnos() {
		new TareaWSObtenerAlumnos().execute();
    }
	
	private AlumnoClient getAlumnoClient() {
        
        String requestURI = SianetApplication.getRequestURI(getActividad());
		if (requestURI != null) {
	        if (client == null || !requestURI.equals(lastRequestURI)) {
	            BasicHttpParams params = new BasicHttpParams();
	            HttpProtocolParams.setVersion(params, HttpVersion.HTTP_1_1);
	            HttpProtocolParams.setContentCharset(params, HTTP.DEFAULT_CONTENT_CHARSET);
	            HttpProtocolParams.setUseExpectContinue(params, false);
//	            client = ProxyFactory.create(AlumnoClient.class, requestURI, new ApacheHttpClient4Executor(params));
	            client = new AlumnoHttpClient(getActividad());
	            lastRequestURI = requestURI;
	        }
	        return client;
		} else
			return null;
		
	}
	
	private class TareaWSObtenerAlumnos extends AsyncTask<String,Integer,List<Alumno>> {
		
		@Override
        protected void onPreExecute(){ 
           super.onPreExecute();
           
           progressDialog = new ProgressDialog(getActividad());
           progressDialog.setCancelable(false);
           progressDialog.show();        
           progressDialog.setContentView(R.layout.custom_progressdialog);

        }
		
		@Override
		protected List<Alumno> doInBackground(String... params) {

			if (cd.hayConexionAInternet()) {
				try {
					AlumnoClient client = getAlumnoClient();
					if (client != null)
						return client.getAlumnoByFamilia(SessionManager.usuarioLogeado());
					else
						return null;
				} catch (Exception ex) {
					return new ArrayList<Alumno>();
				}
			} else
				return null;
			
		}
		
		protected void onPostExecute(List<Alumno> alumnos) {
			
			progressDialog.dismiss();
			
			if (alumnos == null) {
				switchFragment(new NetworkLostFragment());
				return;
			}
			
			if (alumnos.size() > 0) {
	            	
				List<Alumno> mAlumnos = alumnos;

		        AlumnoArrayAdapter adapter = new  AlumnoArrayAdapter(getActividad(), R.layout.mishijos_list, mAlumnos);
				ListView lv = (ListView) getActividad().findViewById(R.id.lv_mishijos);
				lv.setAdapter(adapter);
				
				lv.setOnItemClickListener(new OnItemClickListener() {
					
		            @Override
		            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
		                onSelectedHijoItemClick(parent, view, position, id);
		            }
	            
				});
	            	
			} else {
	            	
				AlertDialogManager.showToastMessage(getActividad(), getString(R.string.no_hay_hijos_registrados));
	            	
			}
			
		}
		
	}
	
	private Activity getActividad(){
		return this.getActivity();
	}
	
}
